import { InputNumber, Select } from 'antd';
import { useState, useEffect, useRef } from 'react';
import FieldWrapper from '../FieldWrapper';

export const SelectRangeInput = (props) => {
  const { value, onChange, options, placeholder = '请输入', defaultSelectValue, style = {}, handleChangeSelectType } = props;
  const [selectValue, setSelectValue] = useState(defaultSelectValue);
  const [minValue, setMinValue] = useState(null);
  const [maxValue, setMaxValue] = useState(null);

  const isInit = useRef(true);

  useEffect(()=>{
    if(isInit.current && value){
      isInit.current = false;
      setMinValue(value[selectValue + 'Min']);
      setMaxValue(value[selectValue + 'Max']);
    }
  }, [value])

  const handleSelectChange = (value) => {
    // 下拉框值改变时，清空输入框
    setMinValue('');
    setMaxValue('');
    triggerChange({ [selectValue + 'Min']: '', [selectValue + 'Max']: '' });
    setSelectValue(value);
    handleChangeSelectType?.(value);
  };

  const handleMinChange = (value) => {
    isInit.current = false;
    setMinValue(value);
    triggerChange({ [selectValue + 'Min']: value });
  };
  const handleMaxChange = (value) => {
    isInit.current = false;
    setMaxValue(value);
    triggerChange({ [selectValue + 'Max']: value });
  };

  const triggerChange = (changedValue) => {
    onChange?.({ ...value, ...changedValue });
  };

  return (
    <FieldWrapper label={<Select value={selectValue} onChange={handleSelectChange} popupClassName="filter-select" options={options} style={{...style}}></Select>}>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <InputNumber value={minValue} onChange={(v) => handleMinChange(v)} width={36} controls={false} min={0} placeholder={placeholder} onPressEnter={props?.onPressEnter} />
        <span className="input-bettwen-line">-</span>
        <InputNumber value={maxValue} onChange={(v) => handleMaxChange(v)} width={36} controls={false} min={0} placeholder={placeholder} onPressEnter={props?.onPressEnter} />
      </div>
    </FieldWrapper>
  );
};
